var ws=null;//当前窗口对象
var uid=null, avatar;//用户ID
var doctorid = null;//医生id、对方Id
var page = 0;//页数
var lastid = 0;//定时获取最新消息
var firstid = 0;
var imageViewer = null;
var tt, doc;
document.addEventListener('plusready',function(){
	imageViewer = new mui.ImageViewer('.msg-content-image', {
		dbl: false
	});
	ws = plus.webview.currentWebview();
	uid = plus.storage.getItem('uid');
	avatar = plus.storage.getItem('userAvatar');
	if(!avatar){avatar = '../images/logo.png';}else{avatar = getAvatar(avatar);}
	doctorid = ws.doctorid;
	$("#loadHistory").show();
	findChatsByfid();
	doc = document.getElementById('msg-list');
	doc.addEventListener('scroll',function(){
		var scrollTop = doc.scrollTop;
		if(scrollTop==0){
			$("#loadHistory").show();
			findChatHistory();			
			clearInterval(tt);
			tt = setInterval(setlastid,1500);
		}  
	}) 
	//点击发送
	$('.sendMessage').on('tap', function(){
		var message = $('#msg-text').val();
		if(!message.trim()){
			toast('消息内容不能为空');
		}else{
			sendMessage(message);
		}
	})
	//选择拍照添加
	$('.paizhao').on('tap', function(){
		var cmr = plus.camera.getCamera();
		cmr.captureImage(function(path) {
			files.push({name:"uploadkey",path:"file://" + plus.io.convertLocalFileSystemURL(path)});
			sendPicture(1 , "file://" + plus.io.convertLocalFileSystemURL(path));
		}, function(err) {});
	})
	//选择相册添加
	$('.photo').on('tap', function(){
		plus.gallery.pick(function(path) {
			files.push({name:"uploadkey",path:path});
			sendPicture(1 ,"file://" + plus.io.convertLocalFileSystemURL(path));
		}, function(err) {}, null);
	})
},false); 
function empty(){
	$("#loadHistory").show();
}
/** 
 * 读取用户与好友的聊天内容；
 * @param int uid  //用户id 
 **/
function findChatsByfid(){ 
	console.log(apiRoot+'?m=home&c=Chat&a=findChatsByfid&uid='+uid+'&doctorid='+doctorid+'&page='+page) 
	$.ajax({
		type:"get", 
		url:apiRoot,
		dataType:'json',
		data:'?m=home&c=Chat&a=findChatsByfid&uid='+uid+'&doctorid='+doctorid+'&page='+page,
		success:function(data){
//			console.log(JSON.stringify(data));
			$("#loadHistory").hide();
			for(var i=0;i<data.length;i++){
				if(i==data.length-1){lastid =data[i].aid;}
			}
			console.log(lastid);
			tt = setInterval(setlastid,2500);//定时加载最新的消息
			if(data.length > 0){ 
				bindHtml(data);
			}
		},
		error:function(e){
			$("#loadHistory").hide(); 
			console.log(JSON.stringify(e));
			errortoast();
		}
	});
}
/**
 * 将聊天内容记载显示在页面
 **/
var msgTypeArr = new Array('text','image','sound');
function bindHtml(data,tory){
//	console.log(JSON.stringify(data));
	plus.nativeUI.closeWaiting();
	if(!data){return ;}
	var html = '';
	for(var i=0;i<data.length;i++){
		if(i==data.length-1){firstid =data[0].aid;}
		var sendAvatar = "";
		if(!data[i].sendAvatar){sendAvatar = '../images/logo.png';}else{sendAvatar = getAvatar(data[i].sendAvatar);}
		 html += '<div class="time">'+data[i].timeStr+'</div><div class="msg-item '+(data[i].sendid==uid ? 'msg-item-self' : '')+'" msg-type="'+msgTypeArr[data[i].type]+'" msg-content="'+data[i].message+'">';
		 html += '<img class="'+(data[i].sendid==uid ? 'msg-user-img-self' : 'msg-user-img-friend')+'" src="'+sendAvatar+'" alt="" />';
		 html += '<div class="msg-content" msgid="'+data[i].aid+'"><div class="msg-content-inner">';
		 if(msgTypeArr[data[i].type]=='text'){
		 	html += ''+data[i].message;
		 }else if(msgTypeArr[data[i].type]=='image'){ 
		 	var pic = '';
		 	if(data[i].message){pic = getAvatar(data[i].message);}
		 	html += '<img class="msg-content-image" src="'+pic+'" style="max-width: 100px;" />';
		 }
		 html += '</div><div class="msg-content-arrow"></div></div><div class="mui-item-clear"></div></div>';
	}
	imageViewer.findAllImage(); 
	if(tory == 1){
		$("#msg-list").prepend(html);
		page++;
		doc.scrollTop = 0;
	}else{
		$("#msg-list").append(html);
		doc.scrollTop = doc.scrollHeight + doc.offsetHeight;
	}
}
/**
 * 发送文字消息
 *
 * @param int uid  //用户id
 * @param int doctorid  //医生id
 * @param int message  //发送消息
 * @return 无 
 **/
function sendMessage(message){
//	console.log('m=home&c=Chat&a=sendMessage&uid='+uid+'&doctorid='+doctorid+'&message='+message)
	if(!message.trim() || message.trim()==''){
		toast('发送内容不能为空哦');		
		return ; 
	}
	var nowtime = new Date().getHours()+":"+new Date().getMinutes()+":"+new Date().getSeconds();
	$.ajax({ 
		type:"get", 
		url:apiRoot,
		dataType:'json',
		data:'m=home&c=Chat&a=sendMessage&sendid='+uid+'&receiveid='+doctorid+'&message='+message+'&type=0',//type=0->图文聊天
		success:function(data){
			plus.nativeUI.closeWaiting();
			clearInterval(tt);
			lastid = data;
			console.log(lastid);
			if(data>0){ 
				var html = '<div class="time">'+nowtime+'</div><div class="msg-item msg-item-self " msg-type="text" msg-content="'+message+'">';
				html += '<img class="msg-user-img-self" src="'+avatar+'" alt="" />';
				html += '<div class="msg-content"><div class="msg-content-inner">'+message+'</div><div class="msg-content-arrow"></div></div><div class="mui-item-clear"></div></div>';
				$("#msg-list").append(html); 
				$('#msg-text').val('');
				doc.scrollTop = doc.scrollHeight + doc.offsetHeight;
				tt = setInterval(setlastid,1500);
			}
		},
		error:function(e){
			plus.nativeUI.closeWaiting();
			console.log(JSON.stringify(e));
			errortoast();
		}
	});
	
}
/**
 * 发送图片消息
 *
 * @param int uid  //用户id
 * @param int doctorid  //医生id
 * @param int message  //发送消息
 * @return 无 
 **/
var soundNum = -1;
var uploading = 0; 
var files = [];
function sendPicture(type , path){  
	var sound = 0;
	if(type == 2){
		sound = 1;
	}
	if(uploading==1){toast('已在上传，请稍后再继续上传。');return ;}
	uploading = 1;
	if(files.length<=0){    
		plus.nativeUI.alert("没有添加上传文件！");
		return;
	}
	var w = plus.nativeUI.showWaiting('上传中...');
	toast('正在上传请稍候！');
	var nowtime = new Date().getHours()+":"+new Date().getMinutes()+":"+new Date().getSeconds();
	var pic = ''; 
	var server = apiRoot + '?m=Home&c=member&a=uploadOne';
	var task=plus.uploader.createUpload(server,
		{method:"POST"}, 
		function(t,status){ //上传完成
			plus.nativeUI.closeWaiting();
			if(status==200){ 
				uploading = 0;
				pic = t.responseText; 
				console.log(pic);
				mui.get(apiRoot+'?m=home&c=Chat&a=sendMessage&sendid='+uid+'&receiveid='+doctorid+'&message='+pic+'&type=1', function(data){
					clearInterval(tt);
					lastid = data;
					var html = '<div class="time">'+nowtime+'</div><div class="msg-item msg-item-self " msg-type="image" msg-content="'+path+'">';
					html += '<img class="msg-user-img-self" src="'+avatar+'" alt="" />';
					html += '<div class="msg-content"><div class="msg-content-inner"><img class="msg-content-image" src="'+path+'" style="max-width: 100px;" /></div><div class="msg-content-arrow"></div></div><div class="mui-item-clear"></div></div>';
					$("#msg-list").append(html);
					toast("上传成功");
					w.close();
					$('.alert').addClass('dis');
					$('.chamber-comment-nav').css('height','50px');
					doc.scrollTop = doc.scrollHeight + doc.offsetHeight;
					tt = setInterval(setlastid,1500);
				},'json');
			}else{
				toast("上传失败："+status);
			}
		}
	);
	for(var i=0;i<files.length;i++){
		var f=files[i];
		task.addFile(f.path,{key:f.name});
	}
	task.start();
	imageViewer.findAllImage();
}
/**
 * 下旬历史信息 
 *
 * @param int uid  //用户id
 * @param int doctorid  //医生id
 * @param int message  //发送消息
 * @return 无 
 **/ 
function findChatHistory(){
	console.log(apiRoot + '?m=home&c=Chat&a=findChatsByfid&uid='+uid+'&doctorid='+doctorid+'&firstid='+firstid+'&page='+page);
	$.ajax({
		type:"get",
		url:apiRoot,  
		dataType:'json',
		data:'m=home&c=Chat&a=findChatsByfid&uid='+uid+'&doctorid='+doctorid+'&firstid='+firstid+'&page='+page,
		success:function(data){
			$("#loadHistory").hide();
			plus.nativeUI.closeWaiting(); 
//			console.log(JSON.stringify(data)); 
			if(data.length > 0){ 
				var tory = 1;
				bindHtml(data,tory);
			}else{
				toast('没有更多消息了！');
				doc.scrollTop = 0;
			}
		},
		error:function(e){
			$("#loadHistory").hide();
			console.log(JSON.stringify(e));
			errortoast();
		}
	});
}
//定时刷新数据
function setlastid(){
	$.ajax({
		type:"get",
		url:apiRoot,  
		dataType:'json',
		data:'m=home&c=Chat&a=findNewByfid&uid='+uid+'&doctorid='+doctorid+'&lastid='+lastid,
		success:function(data){
			plus.nativeUI.closeWaiting(); 
//			console.log(JSON.stringify(data)); 
			if(data.length > 0){ 
				for(var i=0;i<data.length;i++){
					if(i==data.length-1){lastid =data[i].aid;}
				}
//				console.log(lastid);
				var tory = 2;
				bindHtml(data,tory);
			}
		},
		error:function(e){
			console.log(JSON.stringify(e));
		}
	});
}
tt = setInterval(setlastid,1500);
